$(document).ready(function () {
  //给三个按钮添加点击事件
  $("#goodsList").bind("click", function () {
    loadHTML("goodsList");
  });
  $("#addGoods").bind("click", function () {
    loadHTML("addGoods");
  });
  $("#orderList").bind("click", function () {
    loadHTML("orderList");
  });
});

//点击按钮加载main里面的html
function loadHTML(a) {
  $.ajax({
    url: `../${a}/${a}.html`,
    cache: true,
    async: false,
    xhrFields: {
      withCredentials: true
    },
    success: function (html) {
      $("#mainBox").html(html);
    }
  });
}

//上传图片函数
function uploadPic(content) {
  if (content === "") {} else {
    var fd = new FormData();
    fd.append("file", content.files[0]);
    $.ajax({
        type: "POST",
        data: fd,
        url: "../php/uploadimg.php",
        contentType: false,
        processData: false,
        cache: false
      })
      .done(function () {})
      .fail(function () {});
  }
}

//检查表单是否完成
function checkBlank() {
  //name不为空
  let value = document.getElementById("name").value;
  if (value === "") {
    document.getElementById(`name_tip`).className = "";
    document.getElementById(`name_tip`).className = "";
    document.getElementById(`name_tip`).innerText = "   不能为空";
  } else {
    document.getElementById(`name_tip`).className = "";
    document.getElementById(`name_tip`).className = "";
    document.getElementById(`name_tip`).innerText = "";
  }

  //symbol不为空
  let symbol = document.getElementById("symbol").value;
  if (symbol === "") {
    document.getElementById(`symbol_tip`).className = "";
    document.getElementById(`symbol_tip`).className = "";
    document.getElementById(`symbol_tip`).innerText = "   不能为空";
  } else {
    document.getElementById(`symbol_tip`).className = "";
    document.getElementById(`symbol_tip`).className = "";
    document.getElementById(`symbol_tip`).innerText = "";
  }

  //现价原价限定数字
  let nowPrice = document.getElementById("nowPrice").value;
  let originPrice = document.getElementById("originPrice").value;
  if (
    checkNumber(nowPrice) &&
    checkNumber(originPrice) &&
    parseFloat(nowPrice) <= parseFloat(originPrice)
  ) {
    document.getElementById(`price_tip`).className = "";
    document.getElementById(`price_tip`).className = "";
    document.getElementById(`price_tip`).innerText = "";
  } else {
    document.getElementById(`price_tip`).className = "";
    document.getElementById(`price_tip`).className = "";
    document.getElementById(`price_tip`).innerText = "   请输入准确数字(现价低于原价)";
  }

  //主图片不能为空
  let picvalue = document.getElementsByClassName("filetext form")[0].value;
  if (picvalue === "") {
    document.getElementById("mainpic_tip").className = "";
    document.getElementById("mainpic_tip").className = "";
    document.getElementById("mainpic_tip").innerText = "请选择图片";
  } else {
    document.getElementById("mainpic_tip").className = "";
    document.getElementById("mainpic_tip").className = "";
    document.getElementById("mainpic_tip").innerText = "";
  }

  //检查返回值
  if (
    document.getElementById(`name_tip`).innerText === "" &&
    document.getElementById(`price_tip`).innerText === "" &&
    document.getElementById("mainpic_tip").innerText === "" &&
    document.getElementById("symbol_tip").innerText === ""
  ) {
    return true;
  } else {
    return false;
  }
}
//获取整个表单的所有数据
function getData() {
  //获取那些input框中的值
  let name = document.getElementById("name").value;
  let originPrice = document.getElementById("originPrice").value;
  let nowPrice = document.getElementById("nowPrice").value;
  let symbol = document.getElementById("symbol").value;
  let imgUrl = "../../upload";

  //把两个图片路径给定
  let mainImg = `${imgUrl}/${document.getElementsByClassName("filetext form")[0].value}`;
  let referImg = `${imgUrl}/${document.getElementsByClassName("referImg")[0].value}`;

  //detailImg的获取
  let detailImg = [];
  let pics = document.getElementById("referpicTable").getElementsByTagName("tbody")[0].getElementsByTagName("tr");
  for (let i = 0; i < pics.length; i++) {
    let Img = `${imgUrl}/${pics[i].getElementsByClassName("filetext form")[0].value}`;
    detailImg.push(Img);
  }
  //套餐set 评论 commits的获取
  let set = document.getElementById("addSetTable").getElementsByTagName("tr");
  let sets = [];
  for (let i = 0; i < set.length; i++) {
    let name = set[i].getElementsByTagName("td")[0].innerText;
    let price = set[i].getElementsByTagName("td")[1].innerText;

    let s = {
      price,
      name
    }
    sets.push(s);
  }

  let commit = document
    .getElementById("addCommitTable")
    .getElementsByTagName("tr"); //有多少 条评论
  let commits = [];
  for (let i = 0; i < commit.length; i++) {
    let s = commit[i].getElementsByTagName("td")[0].innerText;
    commits.push(s);
  }

  //获取种类并用JSON打包
  let cate = document.getElementById("cateTable").getElementsByTagName("table");
  let cates = [];
  for (let i = 0; i < cate.length; i++) {
    let ca = {};
    let a = cate[i].getElementsByTagName("tr")[1].getElementsByTagName("td")[0]
      .innerText;
    ca.stylename = a;
    let mm = [];
    let b = cate[i].getElementsByTagName("tr");
    for (let i = 1; i < b.length; i++) {
      let nn = {};
      let at = b[i].getElementsByTagName("td")[1].innerText;
      let picString = b[i].getElementsByClassName("filetext form")[0].value;
      nn.attri = at;
      nn.pic = `${imgUrl}/${picString}`;
      mm.push(nn);
    }
    ca.style = mm;
    cates.push(ca);
  }

  sets = JSON.stringify(sets);
  cates = JSON.stringify(cates);
  commits = JSON.stringify(commits);
  detailImg = JSON.stringify(detailImg);


  let data = {
    name,
    mainImg,
    detailImg,
    referImg,
    originPrice,
    nowPrice,
    sets,
    symbol,
    commits,
    cates
  };

  return data;
}
//添加评论的函数
function addList(buttonId, contentId, inputID) {
  document.getElementById(buttonId).addEventListener("click", function () {
    //检查一下不为空才能添加
    if (document.getElementById(inputID).value != "") {
      let tr = document.createElement("tr");
      tr.innerHTML = `<td>${document.getElementById(inputID).value}</td>
                        <td class="buttonTd">
                             <button class="Button">删除</button>
                        </td>`;
      tr
        .getElementsByClassName("Button")[0]
        .addEventListener("click", function () {
          let tr = this.parentNode.parentNode;
          tr.parentNode.removeChild(tr);
        });
      document
        .getElementById(contentId)
        .getElementsByTagName("tbody")[0]
        .appendChild(tr);
      document.getElementById(inputID).value = "";
    }
  });
}
//添加套餐的函数
function addSetTable(buttonId, contentId, inputID, inputID2) {
  document.getElementById(buttonId).addEventListener("click", function () {
    //检查一下不为空才能添加
    if (document.getElementById(inputID).value != "" && document.getElementById(inputID2).value != "") {
      let tr = document.createElement("tr");
      tr.innerHTML = `<td>${document.getElementById(inputID).value}</td>
                      <td>${document.getElementById(inputID2).value}</td>
                        <td class="buttonTd">
                             <button class="Button">删除</button>
                        </td>`;
      tr
        .getElementsByClassName("Button")[0]
        .addEventListener("click", function () {
          let tr = this.parentNode.parentNode;
          tr.parentNode.removeChild(tr);
        });
      document
        .getElementById(contentId)
        .getElementsByTagName("tbody")[0]
        .appendChild(tr);
      document.getElementById(inputID).value = "";
      document.getElementById(inputID2).value = "";

    }
  });
}

//点击确认添加类型
function addCategory() {
  document.getElementById("addCategory").addEventListener("click", function () {
    //检查一下不为空才能添加
    if (
      document.getElementById("cateInput").value != "" &&
      document.getElementById("attriInput").value != ""
    ) {
      let table = document.createElement("table");
      table.className = "tableStyle cateT";
      table.innerHTML = `
        <tbody>
        <tr>
            <th>类别</th>
            <th>参数</th>
            <th class="buttonTd">
                <button class="Button">删除</button>
            </th>
        </tr>
        </tbody>`;
      let cate = document.getElementById("cateInput").value;
      let attri = document.getElementById("attriInput").value;
      let attris = [];
      attris = attri.split("#");
      attris.forEach(element => {
        let tr = document.createElement("tr");
        tr.innerHTML = `<td>${cate}</td>
                            <td>${element}</td>
                            <td><span class="inputFaker">
                              <button class="changeFlieBtn Button">上传图片</button>
                              <input type="text" class="filetext form" disabled/>
                              <input type="file" class="truefile">
                              </span>
                            </td>`;
        tr
          .getElementsByClassName("changeFlieBtn")[0]
          .addEventListener("click", function () {
            let trueflie = tr.getElementsByClassName("truefile")[0];
            trueflie.click();

            trueflie.addEventListener("input", function () {
              tr.getElementsByClassName("filetext")[0].value = cutImgName(
                trueflie.value
              );
            });
          });
        table.getElementsByTagName("tbody")[0].appendChild(tr);
      });
      table
        .getElementsByClassName("Button")[0]
        .addEventListener("click", function () {
          let table = this.parentNode.parentNode.parentNode.parentNode;
          table.parentNode.removeChild(table);
        });
      document.getElementById("cateTable").appendChild(table);

      document.getElementById("cateInput").value = "";
      document.getElementById("attriInput").value = "";
    }
  });
}
//拆解路径字符串得到文件名
function cutImgName(str) {
  let strs = [];
  strs = str.split(/[\\\/]/);
  return strs[strs.length - 1];
}
//只能输入整数或者小数
function checkNumber(val) {
  let reg = /^[0-9]+([.]{1}[0-9]+){0,1}$/;
  return reg.test(val);
}

//上传样式修改功能关联
function inputStyleChange(i) {
  document
    .getElementsByClassName("changeFlieBtn")[i].addEventListener("click", function () {
      let trueflie = document.getElementsByClassName("truefile")[i];
      trueflie.click();

      trueflie.addEventListener("input", function () {
        document.getElementsByClassName("filetext")[i].value = cutImgName(
          trueflie.value
        );
      });
    });
}

function insertAfter(newElement, targetElement) {
  var parent = targetElement.parentNode;
  if (parent.lastChild == targetElement) {
    parent.appendChild(newElement);
  } else {
    parent.insertBefore(newElement, targetElement.nextSibling);
  }
}

function addMoreDetaiImg() {
  document.getElementById("addMoreDetaiImg").addEventListener("click", function () {
    let table = document.getElementById("referpicTable").getElementsByTagName("tbody")[0];

    let tr = document.createElement("tr");
    tr.innerHTML = `
  <td>
  <span class="inputFaker">
          <button class="changeFlieBtn Button">上传图片</button>
          <input type="text" class="filetext form" disabled/>
          <input type="file" class="truefile">
  </span>
  </td>
  <td>
  <button class="Button">删除</button>
  </td>
  `;

    tr
      .getElementsByClassName("changeFlieBtn")[0]
      .addEventListener("click", function () {
        let trueflie = tr.getElementsByClassName("truefile")[0];
        trueflie.click();

        trueflie.addEventListener("input", function () {
          tr.getElementsByClassName("filetext")[0].value = cutImgName(
            trueflie.value
          );
        });
      });

    tr.getElementsByClassName("Button")[1].addEventListener("click", function () {
      let tr = this.parentNode.parentNode;
      tr.parentNode.removeChild(tr);
    })

    table.appendChild(tr);
  })
}